#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "list.h"
#include "def.h"

typedef int datatype;

typedef struct kernel{
    int data;
    struct list_head my;
}kernel,*pklist;

pklist creat_head(){
    pklist head = (pklist)malloc(sizeof(kernel));
    if(head == NULL){
        printf("malloc err\n");
        return NULL;
    }
    INIT_LIST_HEAD(&(head->my));
    return head;
}

pklist creat_node(datatype data){
    pklist node=creat_head();
    if(node == NULL){
        printf("create head err\n");
        return NULL;
    }
    node->data=data;
    return node;
}

static void list_add(struct list_head* new,struct list_head* head){
    __list_add(new,head,head->next);
}


void insert_head(pklist head,datatype data){
    pklist new = creat_node(data);
    if(new == NULL){
        printf("create new err\n");
        return ;
    }
    list_add(&(new->my),&(head->my));
    
}


void show(const pklist head){
    struct list_head* pos=NULL;
    pklist node = NULL;
    list_for_each(pos,&(head->my)){
        node = list_entry(pos,struct kernel,my);
        printf("%d ",node->data);
    }
    printf("\n");

}


void showmid(const pklist head,int len){
    struct list_head* pos=NULL;
    pklist node = NULL;
    int i=0;
    list_for_each(pos,&(head->my)){
        i++;
        if(i == len){   //遍历找到len位置的数
            node = list_entry(pos,struct kernel,my);
            break;
        }
    }
    printf("中间值为:%d\n",node->data);

}

void showmidou(const pklist head,int len){
    struct list_head* pos=NULL;
    pklist node1 = NULL;
    pklist node2 = NULL;
    int i=0;
    list_for_each(pos,&(head->my)){
        i++;
        if(i == len){
            break;
        }
    }
    node1 = list_entry(pos,struct kernel,my);
    node2 = list_entry(pos->next,struct kernel,my);
    printf("%d %d\n",node1->data,node2->data);
    float data=( (float)(node1->data + node2->data) / 2  );
    printf("平均值为:%.1f\n",data);

}



int main(void){
    pklist head = creat_head();

    time_t t=time(0);
    srand(t);
    int len=rand()%10+10;

    for(int i=0;i<len;i++){
        datatype data =rand()%10+1;
        insert_head(head,data);
    }
    show(head);
    printf("\n");
    printf("len:%d\n",len);
    if( len%2 == 0 ){
        showmidou(head , (len/2) );
    }else{
        showmid(head , ( ( (len-1) /2) + 1 ));
    }

    return 0;
}